<template>
  <!-- <el-container style="height: auto;"> -->
  <el-container style="height: 100vh">
    <!-- 左侧导航栏 -->
    <el-aside
      width="220px"
      style="background-color: #2f4050; position: relative; z-index: 2"
    >
      <div class="logo">
        <span class="logo-text">列表</span>
      </div>
      <el-menu
        :default-active="currentMenu"
        background-color="#2f4050"
        text-color="#fff"
        active-text-color="#ffd04b"
        @select="handleMenuSelect"
        mode="vertical"
      >
        <el-menu-item
          v-for="menu in mainMenus"
          :key="menu.id"
          :index="menu.id"
          class="menu-item"
          @mouseenter="handleMouseEnter(menu.id, $event)"
          @mouseleave="hideSubMenu"
        >
          <i :class="menu.icon"></i>
          <template #title>
            <span>{{ menu.label }}</span>
          </template>
        </el-menu-item>
      </el-menu>
    </el-aside>

    <!-- 子菜单对话框 -->
    <div
      v-if="activeSubMenu"
      class="submenu-dialog"
      :style="{
        left: '220px',
        top: subMenuTop + 'px',
        position: 'absolute',
      }"
      @mouseenter="keepSubMenuOpen"
      @mouseleave="hideSubMenu"
    >
      <div class="submenu-content">
        <el-tabs v-model="activeTab" type="card" class="category-tabs">
          <el-tab-pane
            v-for="(category, index) in getCurrentSubMenu().categories"
            :key="index"
            :label="category.title"
            :name="category.title"
          >
            <div class="button-grid">
              <el-button
                v-for="(button, btnIndex) in category.buttons"
                :key="btnIndex"
                :size="button.size || 'small'"
                :type="button.type || 'default'"
                :plain="button.plain || false"
                @click="handleButtonClick(button)"
              >
                {{ button.label }}
              </el-button>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>

    <!-- 主内容区域 -->
    <el-container>
      <el-header
        style="
          border-bottom: 1px solid #e6e6e6;
          display: flex;
          justify-content: space-between;
          align-items: center;
          padding: 0 20px;
        "
      >
        <div>
          <span class="header-title">云进销存体验账套</span>
        </div>
        <div style="display: flex; align-items: center">
          <el-button
            type="primary"
            size="mini"
            style="margin-right: 10px"
            @click="login"
          >
            登录
          </el-button>
          <el-button
            type="success"
            size="mini"
            style="margin-right: 20px"
            @click="reg"
          >
            注册
          </el-button>
          <el-dropdown>
            <i class="el-icon-more" style="cursor: pointer"></i>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item>满意问卷</el-dropdown-item>
                <el-dropdown-item>帮助</el-dropdown-item>
                <el-dropdown-item>AI助手</el-dropdown-item>
                <el-dropdown-item>体验</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
          <!-- <span style="margin-left: 20px">17324517707</span> -->
        </div>
      </el-header>

      <!-- 可编辑标签页区域 -->
      <div class="custom-tabs">
        <el-tabs
          v-model="editableTabsValue"
          type="card"
          closable
          @tab-remove="handleTabRemove"
          @tab-click="handleTabClick"
        >
          <el-tab-pane
            v-for="item in editableTabs"
            :key="item.name"
            :label="item.title"
            :name="item.name"
          >
            <!-- 标签页内容由router-view渲染 -->
            <router-view :key="item.name" />
          </el-tab-pane>
        </el-tabs>
      </div>

      <el-main style="padding: 20px; background-color: #f3f4f6">
        <!-- 初始路由视图（标签页未激活时显示） -->
        <router-view v-if="editableTabsValue === ''" />
      </el-main>
    </el-container>
  </el-container>
</template>

<script>
export default {
  name: "CloudInventorySystem",
  data() {
    return {
      currentMenu: "home",
      activeSubMenu: null,
      activeTab: "",
      subMenuTop: 0,
      menuTimer: null,
      // 标签页相关数据
      editableTabsValue: "",
      editableTabs: [
        {
          title: "首页",
          name: "Home",
          route: "Home",
        },
      ],
      // 菜单数据
      mainMenus: [
        { id: "home", label: "首页", icon: "el-icon-home" },
        { id: "purchase", label: "购货", icon: "el-icon-shopping-cart-full" },
        { id: "sales", label: "销货", icon: "el-icon-s-data" },
        { id: "warehouse", label: "仓库", icon: "el-icon-location" },
        { id: "finance", label: "资金", icon: "el-icon-money" },
        { id: "product", label: "商品", icon: "el-icon-goods" },
        { id: "data", label: "资料", icon: "el-icon-menu" },
        { id: "customer", label: "客户经营", icon: "el-icon-user-solid" },
        { id: "settings", label: "设置", icon: "el-icon-setting" },
      ],
      subMenus: {
        purchase: {
          categories: [
            {
              title: "采购单据",
              buttons: [
                { label: "购货订单", route: "PurchaseOrders" },
                { label: "购货单", route: "ShoppingLists" },
                { label: "购货退货单", route: "PurchaseReturnOrder" },
                { label: "智能补货", route: "SmartReplenishment" },
                { label: "采购发票登记", route: "PurchaseInvoiceRegistration" },
                {
                  label: "采购历史价跟踪",
                  route: "PurchaseHistoryPriceTracking",
                },
                { label: "询价单", route: "InquiryForm" },

                { label: "比价单", route: "PriceComparisonList" },
              ],
            },
            {
              title: "采购报表",
              buttons: [
                { label: "采购订单跟踪表", route: "PurchaseOrderTrackingForm" },
                { label: "采购明细表", route: "CommodityPurchaseSchedule" },
                { label: "采购汇总表(按商品)" },
                { label: "采购汇总表(按供应商)" },
                { label: "采购汇总表(按业务员)" },
                { label: "采购付款一览表", route: "PurchasePaymentOverview" },
                {
                  label: "采购订单变更表",
                  route: "PurchaseOrderChangeRequest",
                },
              ],
            },
            {
              title:'单据记录',
              buttons:[
                { label: '购货订单记录', route: 'PurchaseOrderList' },
                { label: '购货单记录', route: 'PurchaseList' },
                { label: '购货退货单记录', route: 'PurchaseReturnOrderList' },
                { label: '采购发票登记记录', route: 'InvoiceRegisterList' },
              ],
            },
          ],
        },
        sales: {
          categories: [
            {
              title: "销售单据",
              buttons: [
                { label: "报价单", route: "saleQuotation" },
                { label: "销货订单", route: "saleOrders" },
                { label: "销货单", route: "salesOrder" },
                { label: "销货退货单", route: "salesReturnOrder" },
                { label: "销售发票登记", route: "salesInvoiceRegistration" },
                { label: "物流服务", route: "logisticsServices" },
              ],
            },
            {
              title: "销售报表",
              buttons: [
                { label: "销售明细表", route: "salesDetails" },
                { label: "销售收款一览表", route: "listOfSalesReceipts" },
                { label: "往来单位欠款表" },
                { label: "销售利润表" },
                { label: "销售排行表" },
                { label: "销售订单变更表" },
              ],
            },
          ],
        },
        warehouse: {
          categories: [
            {
              title: "仓库单据",
              buttons: [
                { label: "调拨单", route: "TransferOrder" },
                { label: "其他入库单", route: "OtherInbound" },
                { label: "其他出库单", route: "OtherOutbound" },
                { label: "成本调整单", route: "AmountAdjustPage" },
                { label: "组装单", route: "AssemblyStoragePage" },
                { label: "拆卸单", route: "DismantlingSheet" },
                { label: "组装拆卸模板", route: "CombinationTemplate" },
              ],
            },
            {
              title: "仓库报表",
              buttons: [
                { label: "商品库存余额表" },
                { label: "商品收发明细表" },
                { label: "商品收发汇总表" },
                { label: "其他出入库明细表" },
                { label: "序列号跟踪表" },
                { label: "序列号状态表" },
                { label: "批次保质期清单" },
                { label: "批次跟踪表" },
              ],
            },
            {
              title: "盘点",
              buttons: [
                { label: "盘点" },
                { label: "盘点记录" },
                { label: "序列号盘点" },
              ],
            },
          ],
        },
        finance: {
          categories: [
            {
              title: "资金单据",
              buttons: [
                { label: "收款单", route: "FinancialReceipts" },
                { label: "预收款单", route: "AdvanceCollections" },
                { label: "付款单", route: "PaymentSlips" },
                { label: "核销单", route: "WriteOffDocument" },
                { label: "其他收入单", route: "OtherIncomeSlips" },
                { label: "其他支出单", route: "OtherExpenditureNotes" },
                {
                  label: "采购销售费用清单",
                  route: "ListOfProcurementAndSalesCosts",
                },
                { label: "资金转账单", route: "FundsTransferSlip" },
                { label: "在线收款明细", route: "OnlinePayoutDetails" },
              ],
            },
            {
              title: "资金报表",
              buttons: [
                { label: "现金银行报表", route: "CashBankStatements" },
                { label: "应付账款明细表", route: "AccountsPayableSchedule" },
                {
                  label: "应收账款明细表",
                  route: "AccountsReceivableStatement",
                },
                {
                  label: "应付账款汇总表",
                  route: "AccountsPayableSummaryStatement",
                },
                {
                  label: "应收账款汇总表",
                  route: "AccountsReceivableSummaryTable",
                },
                { label: "客户对账单", route: "CustomerReconciliationTable" },
                { label: "供应商对账单", route: "SupplierReconciliationSheet" },
                {
                  label: "其他收支明细表",
                  route: "StatementOfOtherIncomeAndExpenditures",
                },
                { label: "利润表", route: "IncomeStatement" },
              ],
            },
            {
              title: "工作台",
              buttons: [{ label: "客户对账工作台" }, { label: "超级对账单" }],
            },
          ],
        },
        product: {
          categories: [
            {
              title: "商品资料",
              buttons: [
                { label: "商品", route: "GoodsManagement" },
                { label: "计量单位", route: "UnitManagement" },
                { label: "商品类别", route: "CategoryManagement" },
                { label: "品牌", route: "BrandManagement" },
                { label: "商品货架", route: "ShelfManagement" },
                { label: "客户物料编码", route: "CustomerMaterial" },
              ],
            },
            {
              title: "商品价格",
              buttons: [
                { label: "商品价格本" },
                { label: "调价方案设置" },
                { label: "商品价格变更表" },
              ],
            },
          ],
        },
        data: {
          categories: [
            {
              title: "基础资料",
              buttons: [
                { label: "客户" ,route:"CustomerManagement"},
                { label: "供应商", route: "VendorS" },
                { label: "仓库" ,route:"WarehouseManagement"},
                { label: "职员", route: "EmployeeS" },
                { label: "账户", route: "AccountManagement" },
                { label: "客户等级" ,route:"CustomerLevelTable" },
                { label: "地区", route: "RegionS" },
                { label: "项目",route:"ProjectList" },
                { label: "部门" ,route:"DepartmentManagement" },
                { label: "发货地址", route: "ShippingAddress" },
                { label: "文件中心", route: "FileCenter" },
                { label: "任务中心", route: "MissionCenter" },
              ],
            },
            {
              title: "辅助资料",
              buttons: [
                { label: "客户类别", route: "CustomerCategories" },
                { label: "供应商类别", route: "VendorClassification" },
                { label: "支出类别", route: "ExpenseType" },
                { label: "收入类别", route: "IncomeType" },
                { label: "结算方式", route: "PayMethod" },
                { label: "单据编码规则", route: "CodeRules" },
                { label: "线路", route: "DataLine" },
                { label: "项目状态", route: "ProjectStatus" },
              ],
            },
          ],
        },
        customer: {
          categories: [
            {
              title: "客户经营",
              buttons: [
                { label: "客户经营概览" },
                { label: "客户分层经营" },
                { label: "客户贡献分析" },
              ],
            },
            {
              title: "工作台",
              buttons: [
                { label: "客户管理工作台" },
                { label: "推荐商品清单" },
                { label: "客户联络分组" },
                { label: "跟进任务" },
                { label: "跟进记录" },
              ],
            },
          ],
        },
        settings: {
          categories: [
            {
              title: "设置",
              buttons: [
                { label: "系统参数", route: "BasicParams" },
                { label: "在线开票设置" },
                { label: "权限设置" },
                { label: "在线打印模板" },
                { label: "在线套打模板" },
                { label: "云打印" },
                { label: "支付通道配置" },
              ],
            },
            {
              title: "系统操作",
              buttons: [
                { label: "结账/反结账" },
                { label: "备份与恢复" },
                { label: "操作日志" },
                { label: "重算成本" },
              ],
            },
          ],
        },
      },
    };
  },
  watch: {
    // 监听路由变化，确保标签页状态同步
    $route(to) {
      this.updateTabsOnRouteChange(to);
    },
    // 监听标签页激活状态变化
    editableTabsValue(newVal) {
      if (newVal && newVal !== this.$route.name) {
        this.$router.push({ name: newVal });
      }
    },
  },
  created() {
    // 初始化时添加首页标签
    this.editableTabs = [
      {
        title: "首页",
        name: "Home",
        route: "Home",
      },
    ];
    this.editableTabsValue = "Home";
  },
  methods: {
    //注册跳转
    reg() {
      this.$router.push({
        name: "Regist",
      });
    },
    //登录跳转
    login() {
      this.$router.push({
        name: "LoginPage",
      });
    },
    // 鼠标进入菜单处理
    handleMouseEnter(menuId, event) {
      if (menuId === "home") {
        this.activeSubMenu = null;
        return;
      }
      if (this.menuTimer) {
        clearTimeout(this.menuTimer);
      }

      const menuItem = event.currentTarget;
      if (menuItem) {
        // 获取菜单项在视口中的位置
        const menuRect = menuItem.getBoundingClientRect();
        // 获取侧边栏的位置和高度
        const asideElement = document.querySelector("el-aside");
        const asideRect = asideElement
          ? asideElement.getBoundingClientRect()
          : { top: 0 };

        // 计算子菜单顶部位置，考虑滚动因素
        this.subMenuTop = menuRect.top - asideRect.top;
      }

      this.menuTimer = setTimeout(() => {
        this.activeSubMenu = menuId;
        const firstCategory = this.subMenus[menuId]?.categories[0]?.title;
        if (firstCategory) {
          this.activeTab = firstCategory;
        }
      }, 150);
    },

    // 标签页点击事件处理
    handleTabClick(tab) {
      const tabName = tab.paneName;
      this.editableTabsValue = tabName;

      // 如果当前路由不是该标签页对应的路由，则进行跳转
      if (this.$route.name !== tabName) {
        this.$router.push({ name: tabName });
      }
    },

    // 添加标签页
    addTab(routeName, title) {
      // 检查是否已存在该标签页
      const exists = this.editableTabs.some((tab) => tab.name === routeName);
      if (!exists) {
        this.editableTabs.push({
          title: title,
          name: routeName,
          route: routeName,
        });
      }
      this.editableTabsValue = routeName;
    },

    // 移除标签页
    handleTabRemove(targetName) {
      const tabs = this.editableTabs;
      let activeName = this.editableTabsValue;

      if (activeName === targetName) {
        tabs.forEach((tab, index) => {
          if (tab.name === targetName) {
            const nextTab = tabs[index + 1] || tabs[index - 1];
            if (nextTab) {
              activeName = nextTab.name;
            } else {
              activeName = "Home"; // 无标签页时返回首页
            }
          }
        });
      }

      this.editableTabsValue = activeName;
      this.editableTabs = tabs.filter((tab) => tab.name !== targetName);

      // 跳转到激活的标签页或首页
      if (activeName) {
        this.$router.push({ name: activeName });
      } else {
        this.$router.push({ name: "Home" });
      }
    },

    // 路由变化时更新标签页
    updateTabsOnRouteChange(route) {
      // 首页处理
      if (route.name === "Home") {
        this.editableTabsValue = "Home";
        return;
      }

      if (route.name) {
        const exists = this.editableTabs.some((tab) => tab.name === route.name);
        if (!exists) {
          // 从菜单数据中获取标题
          const title = this.getTitleByRoute(route.name);
          this.addTab(route.name, title || route.name);
        } else {
          // 确保标签页处于激活状态
          this.editableTabsValue = route.name;
        }
      }
    },

    // 通过路由名称获取标题
    getTitleByRoute(routeName) {
      for (const menuKey in this.subMenus) {
        const categories = this.subMenus[menuKey].categories;
        for (const category of categories) {
          for (const button of category.buttons) {
            if (button.route === routeName) {
              return button.label;
            }
          }
        }
      }
      return routeName;
    },

    // 隐藏子菜单
    hideSubMenu() {
      this.menuTimer = setTimeout(() => {
        this.activeSubMenu = null;
      }, 200);
    },

    // 保持子菜单打开
    keepSubMenuOpen() {
      if (this.menuTimer) {
        clearTimeout(this.menuTimer);
      }
    },

    // 获取当前子菜单
    getCurrentSubMenu() {
      return this.subMenus[this.activeSubMenu] || { categories: [] };
    },

    // 菜单选择处理
    handleMenuSelect(index) {
      this.currentMenu = index;
      this.activeSubMenu = null;
      if (index === "home") {
        this.$router.push({ name: "Home" });
        this.editableTabsValue = "Home";
      } else {
        const firstButton = this.subMenus[index]?.categories[0]?.buttons[0];
        if (firstButton && firstButton.route) {
          this.addTab(firstButton.route, firstButton.label);
          this.$router.push({ name: firstButton.route });
        }
      }
    },

    // 按钮点击处理
    handleButtonClick(button) {
      if (button.route) {
        // 添加标签页并导航
        this.addTab(button.route, button.label);
        this.$router.push({ name: button.route });
      }
    },
  },
  beforeUnmount() {
    if (this.menuTimer) {
      clearTimeout(this.menuTimer);
    }
  },
};
</script>

<style scoped>
/* 左侧导航样式 */
.logo {
  padding: 20px;
  text-align: center;
  background: #1f2d3d;
  color: #fff;
}

.logo-text {
  font-size: 16px;
  font-weight: bold;
}

.menu-item {
  position: relative;
}

/* 子菜单对话框样式 */
.submenu-dialog {
  position: absolute;
  width: 600px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  z-index: 3;
  padding: 10px;
  transition: opacity 0.2s ease-in-out;
}

.submenu-content {
  height: 350px;
  overflow: auto;
}

.category-tabs {
  height: 100%;
}

.button-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 10px;
  padding: 10px;
}

/* 头部样式 */
.el-header {
  background-color: #fff;
  color: #333;
  box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
}

.header-title {
  font-size: 16px;
  font-weight: 500;
}

/* 主内容样式 */
.el-main {
  padding: 0;
}

/* 自定义标签页样式 */
.custom-tabs {
  background: #fff;
  padding: 0 20px;
  box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
  z-index: 1;
  position: relative;
}

.custom-tabs .el-tabs__header {
  margin: 0;
  border-bottom: 1px solid #ebeef5;
}

.custom-tabs .el-tabs__nav {
  border: none !important;
}

.custom-tabs .el-tabs__item {
  height: 32px;
  line-height: 32px;
  font-size: 12px;
  padding: 0 12px;
}

.custom-tabs .el-tabs__item.is-active {
  color: #409eff;
  font-weight: 500;
  border-bottom: 2px solid #409eff;
  margin-bottom: -1px;
}
</style>    